﻿using System.ComponentModel;
using System.Linq;
using System.Windows;
using Fayshine.VA.Helpers;
using Fayshine.VA.RIAService.Web;
using Fayshine.VA.Controls;
using System.Collections.Generic;
using System.Collections.ObjectModel;

namespace Fayshine.VA.ViewModels
{
    public class UserRoleViewModel : INotifyPropertyChanged
    {
        #region Private Fields

        private FayshineDomainContext m_Context = null;
        private bool m_HasChanges = false;
        #endregion

        #region Constructor

        public UserRoleViewModel()
        {
            this.Users = new PagedObservableCollectionView<user>();
            this.Roles = new PagedObservableCollectionView<role>();
            this.SelectedRoleUser = new PagedObservableCollectionView<user>();
            m_Context = new FayshineDomainContext();

        }

        #endregion

        #region Properties

        public PagedObservableCollectionView<user> Users
        {
            get;
            set;
        }

        public PagedObservableCollectionView<role> Roles
        {
            set;
            get;
        }

        public PagedObservableCollectionView<user> SelectedRoleUser
        {
            set;
            get;
        }

        public bool HasChanges
        {
            set
            {
                if (m_HasChanges != value)
                {
                    m_HasChanges = value;
                    NofityPropertyChanged("HasChanges");
                }
            }
            get
            {
                return m_HasChanges;
            }
        }

        #endregion

        #region Public Methods

        public void RefreshHasChanges()
        {
            if (m_Context != null)
            {
                this.HasChanges = m_Context.HasChanges;
            }
        }

        public void GetAllUsers()
        {
            var getUsersQuery = m_Context.GetUsersQuery();
            var loadUsersOperation = m_Context.Load(getUsersQuery, (s) =>
            {
                if (!s.HasError)
                {
                    s.Entities.ToList().ForEach(e =>
                    {
                        this.Users.Add(e);
                    });
                }
                else
                {
                    MessageBox.Show(s.Error.Message + s.Error.StackTrace);
                }
                BusyIndicator indicator = Application.Current.RootVisual as BusyIndicator;
                indicator.IsBusy = false;
            }, true);
        }

        public void GetAllRoles()
        {
            var getRolesQuery = m_Context.GetRolesQuery();
            var loadRolesOperation = m_Context.Load(getRolesQuery, (s) =>
            {

                if (!s.HasError)
                {
                    s.Entities.ToList().ForEach(e =>
                    {

                        this.Roles.Add(e);

                    });
                }
                else
                {
                    MessageBox.Show(s.Error.Message + s.Error.StackTrace);

                }
                this.ResetSelectRole(1);
                BusyIndicator indicator = Application.Current.RootVisual as BusyIndicator;
                indicator.IsBusy = false;

            }, true);
        }

        public void AddUser(user user)
        {
            this.Users.Add(user);
            this.m_Context.users.Add(user);
            SaveData();
        }

        public void Update(user user)
        {
            SaveData();
        }

        public void DeleteUser(user user)
        {
            this.Users.Remove(user);
            this.m_Context.users.Remove(user);
            SaveData();
        }

        public void DeleteUsers(List<user> users)
        {
            users.each(u => {
                this.Users.Remove(u);
                this.m_Context.users.Remove(u);
            });
            SaveData();
        }

        public void SaveData()
        {
            if (this.m_Context.HasChanges)
            {
                this.m_Context.SubmitChanges((s) =>
                {
                    if (s.HasError)
                    {
                        MessageBox.Show("Error occurs,Save Failed!");
                    }
                    RefreshHasChanges();
                }, null);
            }
        }

        public void SaveData2()
        {
            if (this.m_Context.HasChanges)
            {
                this.m_Context.SubmitChanges((s) =>
                {

                    //BusyIndicator indicator = Application.Current.RootVisual as BusyIndicator;

                    //indicator.IsBusy = false;
                    if (s.HasError)
                    {
                        MessageBox.Show("Error occurs,Save Failed!");
                    }
                    else
                    {
                        MessageBox.Show("保存成功！");
                    }
                    RefreshHasChanges();

                }, null);
            }
        }

        public bool ExistUser(string userName)
        {
            return this.Users.Where(u => u.Name.Equals(userName, System.StringComparison.OrdinalIgnoreCase)).Any();
        }

        public void ResetSelectRole(int roleId)
        {
            var role = this.Roles.Where(r => r.ID == roleId).FirstOrDefault();
            if (role != null)
            {
                this.SelectedRoleUser.Clear();
                role.users.each(u => {
                    this.SelectedRoleUser.Add(u);
                });
            }
        }

        #endregion

        #region INotifyPropertyChanged Interface

        public event PropertyChangedEventHandler PropertyChanged;
        public void NofityPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        #endregion

    }

    public class StaticData
    {

        public  List<role> Roles
        {
            get;
            set;
        }

        public  List<vatype> DeviceTypes
        {
            get;
            set;
        }

        public ObservableCollection<area> Areas
        {
            get;
            set;
        }

        public ObservableCollection<areatype> AreaTypes
        {
            get;
            set;
        }

        public StaticData()
        {
            Roles = new List<role>();
            Roles.Add(new role() { ID = 1, Title = "管理员" });
            Roles.Add(new role() { ID = 2, Title = "维护员" });
            Roles.Add(new role() { ID = 3, Title = "普通浏览" });

            DeviceTypes = new List<vatype>();
            DeviceTypes.Add(new vatype() { ID = 1, Name = "T0304" });
            DeviceTypes.Add(new vatype() { ID = 2, Name = "T0108" });

            AreaTypes = new ObservableCollection<areatype>();

            AreaTypes.Add(new areatype() { ID = 1, Name = "店铺" });
            AreaTypes.Add(new areatype() { ID = 2, Name = "门面" });
            AreaTypes.Add(new areatype() { ID = 3, Name = "商场" });

            Areas = new ObservableCollection<area>();

            ShopSettingViewModel model = new ShopSettingViewModel();
            model.GetAllAreas();
            this.Areas = model.Areas; ;

        }

    }
}
